<?php
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
class Answer_m extends Model{
    function Answer_m(){
        parent::Model();
    }
	function getAnswer($username,  $password, $number){
        
        $ver = $this->db->query("SELECT * from users WHERE username = '$username' AND password ='$password'");
        
        if ($ver->num_rows()  == 1){
            $answer = $this->db->query("SELECT * from user_answer WHERE question_id = $number AND user_id='$username'");

            if ($answer->num_rows() > 0){
                foreach($answer->result_array() as $hsl){
                    $result = $hsl;
                }
                return $result;
            }
            else{
                return 0;
            }
        }
		else
			return 0;
    }
	
	function setAnswer($username, $password, $number, $choice)
	{
		$ver = $this->db->query("SELECT id from users WHERE username = '$username' AND password ='$password'");
		
		if ($ver->num_rows()  == 1){
			$user_id = $ver->row()->id;
			
			$ver = $this->db->query("SELECT id from question WHERE number = '$number'");
			$question_id = $ver->row()->id;
			
            $answer = $this->db->query("SELECT * from user_answer WHERE question_id = $question_id AND user_id='$user_id'");
			
            if ($answer->num_rows() < 1){
				$ver = $this->db->query("INSERT INTO user_answer (user_id, question_id, answer) VALUES ('$user_id', '$question_id', '$choice')");
                return $this->db->affected_rows();
            }
            else{
				$ver = $this->db->query("UPDATE user_answer SET answer = $choice WHERE (user_id = '$user_id' AND question_id = $question_id)");
				return $this->db->affected_rows();
            }
        }
		else
			return 0;
	}
	
	function getNumAnswer(){
		$ver = $this->db->count_all('user_answer');
		return $ver;
	}
}

?>